package main

import (
	"flag"
	"fmt"
	"runtime"
	"sync"
	"sync/atomic"
	"time"
	"yan-feeorder/common"
	log "ycx-glog"
)

func doSomething(id int, cond *common.Cond, wg *sync.WaitGroup, runOver *int64) {
	defer wg.Done()

	for {
		cond.Wait()

		//>> start do
		//time.Sleep(1e9)
		log.Infof("ThreadID: %02d => run time: %dms\n", id, 0)
		//<< did, signal next do

		cond.Signal()

		rover := atomic.LoadInt64(runOver)
		if rover < 0 {
			break
		}
		atomic.AddInt64(runOver, -1)
	}
}

func main() {
	{
		// 日志目录
		logDir := common.EnsureDir("./_glog/" + log.LogDirName())
		if runtime.GOOS == "windows" {
			flag.Set("alsologtostderr", "true")
		} else {
			flag.Set("alsologtostderr", "false")
			// 记录严重错误(仅linux有效)
			common.RecordFatal(fmt.Sprintf("./_log/fatal_%s.log", common.TimeFormat(time.Now(), "yyyyMMdd_HHmmss")))
		}
		flag.Set("log_dir", logDir)
		flag.Set("v", "3")
		flag.Parse()
		//
		log.MaxSize = 1024 * 1024 * 10 //10M
		log.DirMaxSize = log.MaxSize * 30
		defer log.Flush()
	}

	/************ 主体功能 ************/

	maxThread := 10
	maxRunTimes := int64(20)
	cond := common.NewCond(5)
	cond.Broadcast()

	log.Infoln(time.Now())
	wg := &sync.WaitGroup{}
	for id := 0; id < maxThread; id++ {
		wg.Add(1)
		go doSomething(id, cond, wg, &maxRunTimes)
	}

	wg.Wait()
	log.Infoln(time.Now())
}
